import { _decorator, Component, easing, instantiate, Label, Node, tween, UITransform, Vec3 } from 'cc';
import { ResourcePool } from './ResourcePool';
import { Global } from './Global';
import { Clips } from './Enums';
import { AudioManger } from './AudioManger';
import { Tools } from './Tools';
const { ccclass, property } = _decorator;

@ccclass('CoinsAction')
export class CoinsAction extends Component {
    @property({ type: Label })
    level_label: Label = null;

    private uiTransform: UITransform;

    start() {
        this.uiTransform = this.node.getComponent(UITransform);
        this.refresh_coins();
    }

    update(deltaTime: number) {
        // 可拓展：更新动画或者效果
    }

    /** 更新金币数显示 */
    refresh_coins() {
        this.level_label.string = Global.cur_coins.toString();
    }

    /**
     * 在指定世界坐标位置显示金币飞行动画，并增加金币数
     * @param num 金币数量
     * @param world_pos 金币飞出位置（世界坐标）
     * @param play_sound 是否播放音效（默认播放）
     */
    async put_coins(num: number, world_pos: Vec3, play_sound: boolean = true) {
        // 更新全局金币数
        Global.cur_coins += num;

        const coinPrefab = ResourcePool.instance.get_prefab("coin");
        if (!coinPrefab) {
            console.warn("Coin prefab not found!");
            return;
        }

        // 将世界坐标转换为本地坐标
        const baseLocalPos = this.uiTransform.convertToNodeSpaceAR(world_pos);

        for (let i = 0; i < num; i++) {
            const coin = instantiate(coinPrefab);
            this.node.addChild(coin);

            // 生成随机偏移量，营造散开效果
            const randomOffset = new Vec3(
                Tools.random_between(-30, 80),
                Tools.random_between(0, 150),
                0
            );

            const startLocalPos = baseLocalPos.clone().add(randomOffset);
            coin.setPosition(startLocalPos);

            // 只有最后一个金币完成时才播放声音和刷新文本
            const isLastCoin = (i === num - 1);

            this.animate_coin(coin, isLastCoin, play_sound);
        }
    }

    /** 执行金币飞行动画 */
    private animate_coin(coin: Node, isLastCoin: boolean, play_sound: boolean) {
        // 旋转方向随机，-1 或 1
        const rotationDir = Math.random() > 0.5 ? 1 : -1;

        tween(coin)
            .to(
                Tools.random_between(0.7, 0.9),
                { position: new Vec3(0, 0, 0), angle: 360 * rotationDir },
                Global.our_easing
            )
            .call(() => {
                if (Global.cur_coins > 0 && play_sound && isLastCoin) {
                    AudioManger.instance.playSound(Clips.coins);
                }
            })
            .to(0.4, { scale: new Vec3(0.2, 0.2, 0.2) }, Global.our_easing)
            .call(() => {
                if (isLastCoin) {
                    this.refresh_coins();
                }
            })
            .removeSelf()
            .start();
    }
}
